package cn.aezo.minions.utils;

import cn.aezo.utils.base.MiscU;
import cn.aezo.utils.base.ValidU;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class WxTokenManager {
    private Logger logger = LoggerFactory.getLogger(WxTokenManager.class);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WxAuthService wxAuthService;

    @Value("${help.wxAppId}")
    private String wxAppId;

    @Value("${help.wxAppSecret}")
    private String wxAppSecret;

    @Value("${help.wxAccessToken}")
    private String wxAccessToken;

    @Value("${help.wxJsapiTicket}")
    private String wxJsapiTicket;

    private static final String AccesstokeUrl =
            "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";

    private static final String JsapiTicketUrl =
            "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi";

    public String getAccessToken() {
        String accessToken = getRedisValueNotExpires(wxAccessToken, null);
        if(ValidU.isEmpty(accessToken)) {
            String url = String.format(AccesstokeUrl, wxAppId, wxAppSecret);

            LinkedHashMap resp = restTemplate.getForObject(url, LinkedHashMap.class);
            logger.info("getAccessToken resp = " + resp);

            if(resp.containsKey("errcode")) {
                throw new RuntimeException("获取token错误信息，msg = " + resp);
            } else {
                accessToken = (String) resp.get("access_token");
                Object expiresIn = resp.get("expires_in");
                setRedisValueWithExpires(wxAccessToken, null, accessToken, expiresIn);
            }
        }

        return accessToken;
    }

    public String getJsapiTicket(String accessToken) {
        String jsapiTicket = getRedisValueNotExpires(wxJsapiTicket, null);
        if(ValidU.isEmpty(jsapiTicket)) {
            String url = String.format(JsapiTicketUrl, accessToken);

            LinkedHashMap resp = restTemplate.getForObject(url, LinkedHashMap.class);
            logger.info("getJsSDKInfo resp = " + resp);

            if(StringUtils.isEmpty(resp.get("errmsg")) || !"ok".equals(resp.get("errmsg"))) {
                throw new RuntimeException("获取ticket错误信息，msg = " + resp);
            } else {
                jsapiTicket = (String) resp.get("ticket");
                Object expiresIn = resp.get("expires_in");
                setRedisValueWithExpires(wxAccessToken, null, jsapiTicket, expiresIn);
            }
        }

        return jsapiTicket;
    }

    public Map<String, Object> getJsSDKInfo(String accessToken) {
        Map<String, Object> retMap = new HashMap<>();

        String jsapiTicket = getJsapiTicket(accessToken);
        if(StringUtils.isEmpty(jsapiTicket)) return retMap;

        return MiscU.Instance.toMap("jsapiTicket", jsapiTicket);
    }

    public String getOpenid(String code) {
        String openid = null;
        if(StringUtils.isEmpty(code)) return openid;

        LinkedHashMap wxMap = wxAuthService.getUserAccessTokenAndOpenid(code);
        if (wxMap == null) return openid;

        openid = (String) wxMap.get("openid");

        return openid;
    }

    /**
     * 获取没有超期的值，超期返回null
     * @param redisKey
     * @param mapKey
     * @return
     */
    private String getRedisValueNotExpires(String redisKey, String mapKey) {
        String value = null;
        if(StringUtils.isEmpty(redisKey)) return value;

        long now = (new Date()).getTime();
        value = redisTemplate.opsForValue().get(redisKey);
        if(StringUtils.isEmpty(value)) return value;

        String[] arr = value.split("#");
        if(now > Long.valueOf(arr[1])) {
            return null;
        } else {
            return value;
        }
    }

    /**
     * 设置过期时间
     * @param redisKey
     * @param mapKey
     * @param value
     * @param expiresIn
     */
    private void setRedisValueWithExpires(String redisKey, String mapKey, String value, Object expiresIn) {
        String valueTemp = null;
        if (!StringUtils.isEmpty(value)) {
            valueTemp = value + "#" + getNowExpiresIn(expiresIn);
        }
        if(valueTemp == null) return;

        if(StringUtils.isEmpty(mapKey)) {
            redisTemplate.opsForValue().set(redisKey, valueTemp);
        } else {
            redisTemplate.opsForHash().put(redisKey, mapKey, valueTemp);
        }
    }

    /**
     * 获取超期时间
     * @param expiresIn
     * @return
     */
    private Long getNowExpiresIn(Object expiresIn) {
        long now = (new Date()).getTime();
        if(expiresIn == null) return now;

        Long expiresMs = Long.valueOf(String.valueOf(expiresIn)) - 15 * 60;
        return expiresMs * 1000 + now;
    }
}
